<template>
  <span :id="id" @click="onClick" class="h-input" :class="{'h-input-focus': focus,'h-input-required': required && !modelValue}">
    <span v-if="box" class="input">
      {{innerValue}}&nbsp;
    </span>
    <input v-else class="input" @keydown.enter="forceChange" :value="innerValue" @input="change" :placeholder="placeholder" @focus="onFocus" @blur="onBlur">
    <span @click="clear" class="iconfont right-icon" v-if="allowClear && !!innerValue">&#xe956;</span>
    <span v-if="!!icon && !innerValue" class="iconfont right-icon" v-html="icon"/>
  </span>
</template>
<script setup>
import {nextTick, shallowRef, watch} from 'vue';
import {createProps} from '@/utils';

defineOptions({name: 'HInput'});

const emits = defineEmits(['update:modelValue', 'click', 'focus', 'blur']);
const props = defineProps({
  box: createProps(Boolean),
  id: createProps(String),
  required: createProps(Boolean),
  allowClear: createProps(Boolean),
  placeholder: createProps(String),
  icon: createProps(String),
  modelValue: createProps(String),
  changeImmediate: createProps(Boolean),
});
const innerValue = shallowRef();
const focus = shallowRef(false);

function forceChange(e) {
  innerValue.value = e.target.value;
  emits('update:modelValue', innerValue.value);
  nextTick(() => {
    emits('blur');
  })
}

function clear() {
  innerValue.value = undefined;
  nextTick(() => {
    emits('update:modelValue', innerValue.value);
    nextTick(() => {
      emits('blur');
    })
  })
}

function onClick() {
  emits('click')
}
function onFocus() {
  focus.value = true;
  nextTick(() => {
    emits('focus');
  })
}

function change(e) {
  innerValue.value = e.target.value;

  nextTick(() => {
    if (props.changeImmediate) {
      forceChange(e)
    }
  })
}

function onBlur() {
  focus.value = false;
  nextTick(() => {
    emits('update:modelValue', innerValue.value);
    nextTick(() => {
      emits('blur');
    })
  })
}

watch(() => props.modelValue, () => {
  nextTick(() => {
    innerValue.value = props.modelValue;
  })
}, {
  immediate: true,
})

</script>
<style scoped lang="less">
.h-input {
  padding: 4px 10px;
  display: inline-flex;
  align-items: center;
  //background: red;
  width: calc(100% - 30px);
  margin: 5px;
  background: white;
  border-radius: 6px;
  border-width: 1px;
  border-style: solid;
  border-color: #d9d9d9;
  transition: all 0.2s;
}

//.h-input:hover {
//  border-color: #4096ff;
//}

.h-input-focus {
  border-color: #4096ff;
  box-shadow: rgba(5, 145, 255, 0.1) 0px 0px 0px 2px;
}

.h-input .input::placeholder {
  color: #bfbfbf;
}

.h-input .right-icon {
  color: #bfbfbf;
  margin-left: 5px;
}
.h-input .input {
  width: 100%;
  border: none;
  outline: none;
}

.h-input-required input,
.h-input-required {
  background: #fef0d0;
}

</style>